<template>
  <el-drawer
      size="30%"
      v-if="showDrawer"
      v-model="drawer"
      :title="formData.id?'修改用户':'添加用户'"
      direction="rtl"
      :before-close="closeDrawer">
    <el-form
      size="small"
      ref="formRef"
      :model="formData"
      status-icon
      :rules="rules"
      label-width="60px"
    >
      <el-form-item  v-if="false"label="编号"  prop="id">
        <el-input v-model="formData.id" />
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
      <el-form-item label="邮件" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="电话" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" />
      </el-form-item>
      <el-form-item label="姓名" prop="fullName">
        <el-input v-model="formData.fullName" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-input v-model="formData.sex" />
      </el-form-item>
      <!-- <el-form-item label="注册日期" prop="registrationDate">
        <el-input v-model="formData.registrationDate" />
      </el-form-item>
      <el-form-item label="最近登录" prop="lastLogin">
        <el-input v-model="formData.lastLogin" />
      </el-form-item> -->
      <el-form-item label="是否是管理员" prop="isRoot">
        <el-input v-model="formData.isRoot" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">{{formData.id?'修改':'添加'}}</el-button>
        <el-button @click="resetForm(formRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup lang="ts">
import {ref,reactive,watch} from 'vue'
import {ElNotification} from 'element-plus'
// 导入element-plus的类型
import type { FormInstance, FormRules } from 'element-plus'
import {$add,$update} from '../../api/admin.js'
const emit = defineEmits(['sync-list'])
// 用于判断是否显示渲染抽屉的变量
const showDrawer = ref(false)
// 抽屉变量
const drawer = ref(false)
watch(drawer,(nval)=>{
  if(nval){
    showDrawer.value = true
  }else{
    setTimeout(() => {
      showDrawer.value = false
    }, 200)
  }
})
// 表单数据
const formData = ref({
    // id: '',
    username:'',
    password:'',
    email:'',
    phoneNumber:'',
    fullName:'',
    sex:'',
    registrationDate:'',
    lastLogin:'',
    isRoot:''
})
// 关闭抽屉
const closeDrawer = ()=>{
  drawer.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 清空表单数据
  formData.value = {
    // id: '',
    username:'',
    password:'',
    email:'',
    phoneNumber:'',
    fullName:'',
    sex:'',
    registrationDate:'',
    lastLogin:'',
    isRoot:''
  }
}
// 定义一个ref对象绑定表单
const formRef = ref<FormInstance>()

// //验证账号
// const validateLoginId = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入角色名称'))
//   } else {
//     callback()
//   }
// }
// //验证密码
// const validateLoginPwd = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入密码'))
//   } else {
//     callback()
//   }
// }
//   //验证姓名
// const validateName = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入姓名'))
//   } else {
//     callback()
//   }
// }
//     //验证号码
// const validatePhone = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入号码'))
//   } else {
//     callback()
//   }
// }
//     //验证角色编号
// const validateRoleId = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入角色id'))
//   } else {
//     callback()
//   }
// }
// //验证对象
// const rules = reactive<FormRules<typeof formData>>({
//   loginId: [{ validator: validateLoginId, trigger: 'blur' }],
//   loginPwd: [{ validator: validateLoginPwd, trigger: 'blur' }],
//   name: [{ validator: validateName, trigger: 'blur' }],
//   phone: [{ validator: validatePhone, trigger: 'blur' }],
//   roleId: [{ validator: validateRoleId, trigger: 'change' }]
// })
// 上传成功
// const uploadSuccess: UploadProps['onSuccess'] = (response) => {
//   let {filename,success} = response
//   if(success){
//     ElNotification({
//       title: '提示',
//       message: '头像上传成功',
//       type: 'success',
//     })
//     // 获取头像地址
//     formData.value.photo = filename
//   }
// }
// // 上传之前
// const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
//   // 图片格式
//   let imgTypes = ['image/jpeg','image/gif','image/png']
//   if (!imgTypes.includes(rawFile.type)) {
//     ElNotification({
//       title: '提示',
//       message: '请上传jpg,gif,png格式的图片',
//       type: 'error',
//     })
//     return false
//   } else if (rawFile.size / 1024 / 1024 > 1) {
//     ElNotification({
//       title: '提示',
//       message: '图片大小不能超过1MB',
//       type: 'error',
//     })
//     return false
//   }
//   return true
// }

//提交表
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let ret = {}
      // 判断是做修改还是添加
      if(formData.value.id){
        console.log(formData.value.id);
        
        ret = await $update(formData.value)
         console.log(ret.code);
      }else{
        console.log(formData.value);
        
        ret = await $add(formData.value)
        // 重置表单
        formRef.value?.resetFields()
             console.log(ret.code);
      }
      if(ret.code==200){
        console.log(ret.code);
        
          ElNotification({
            title: '提示',
            message: ret.message,
            type: 'success',
          })
          // 通知父组件更新列表数据
          emit('sync-list')
        }else{
          ElNotification({
            title: '提示',
            message: ret.message,
            type: 'error',
          })
        }
    } else {
      return false
    }
  })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 暴露成员
defineExpose({
  drawer,
  formData
})

</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader{
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>